/*思路：根据id调用商品详情接口获取商品详情数据*/
const wraperEle = document.querySelector('.wraper')
const contentEle = document.querySelector('.content')

/* *----------------------------1. 获取商品id--------------------- */
function getProductId() {
    //http://www.xiongmaoyouxuan.com/api/detail?id=104686496
    let url = location.href
    let params = url.substring(url.indexOf('?') + 1)
    let arr = params.split('=')
    let id = arr[1]
    return id
}

/*** 2. 根据id调用商品详情接口获取商品详情数据 */
function getProductDetail() {
    let id = getProductId()
    ajaxPromise({
        method: 'get',
        url: 'http://www.xiongmaoyouxuan.com/api/detail',
        data: {
            id
        }
    }).then(res => {
        console.log(res)
        let result = res.data
        let imgArr = res.data.detail.descContentList
        showProductDetail(result, imgArr)
        onGlass(result)
    }).catch(error => {
        console.log('详情页网络请求出错')
    })
}
let ArrayStr = localStorage.getItem('PANDACART') //从locaStorage获取数据
let list = JSON.parse(ArrayStr) || []

/* -------------------------3. 渲染数据到页面 -存到本地-------------------------*/
function showProductDetail(data, imgList) {
    let str = `
            <div class="g-left">
                <div class="m-show">
                    <img src="${data.detail.descContentList[0].image.url}" alt="">
                    <div class="mask"></div>
                </div>
                <ul class="m-choose clearfix">
                    <li><img src="${data.detail.descContentList[0].photo.url}" width="60px" alt="1"></li>
                    <li><img src="${data.detail.descContentList[1].photo.url}" width="60px" alt="2"></li>
                    <li><img src="${data.detail.descContentList[2].photo.url}" width="60px" alt="3"></li>
                    <li><img src="${data.detail.descContentList[3].photo.url}" width="60px" alt="4"></li>
                </ul>
            </div>
            <div class="g-right">
               <!-- 右边放大镜 -->
                <div class="g-right-wrap">
                    <img src="${data.detail.descContentList[0].image.url}" alt="">
                </div>
                <h2><span>${data.shop.platformName}</span><span>包邮</span>${data.share.title}</h2>
                <p>${data.share.text}</p>
                <div class="info">
                    <p>${data.shop.shopScoreText}</p>
                    <p>${data.shop.title}</p>
                    <p>预售时间: ${data.shop.createTime}</p>
                </div>
                <div class="p-add clearfix">
                    <div><span class="price">￥${data.detail.originPrice}</span><span>${data.detail.couponStatus}</span></div>
                    <div><button class="cart-add">领券购买</button></div>
                </div>
            </div>
    `
    let newArr = imgList.map(item => {
        return `
           <img src="${item.image.url}" alt="">
              `
    }).join('')
    wraperEle.innerHTML = str
    contentEle.innerHTML = newArr

    /**-------------------------存到本地----------------------*/
    const addBtn = document.querySelector('.cart-add')
    console.log(addBtn);

    let nameStr = localStorage.getItem('TRUEDATA')
    let nameArr = JSON.parse(nameStr)
    console.log(nameArr);
    addBtn.addEventListener('click', function () {
        if (nameArr != null) {
            let id = getProductId()
            if (id == data.detail.id) {
                let id = data.detail.id
                let title = data.detail.title
                let price = data.detail.tbOriginPrice
                let nickname = data.detail.shop.nickname
                let img = data.detail.image
                let singlePrice = 0
                let obj = {
                    id,
                    title,
                    nickname,
                    price,
                    num: 1,
                    sumPrice: price,
                    img
                }
                if (list.length > 0) {
                    let reaptList = list.some(item => item.id == id)
                    //！！隐式转换一定为布尔值
                    if (!!reaptList) {
                        list.forEach(item => {
                            if (item.id == id) {
                                item.num = item.num + 1
                            }
                        })
                    } else {
                        list.push(obj)
                    }
                } else {
                    list.push(obj)
                }
                localStorage.setItem('PANDACART', JSON.stringify(list))
                if (confirm('加入购物车成功，是否要调转去购物车？')) {
                    location.href = 'cart.html'
                }
            }
        } else {
            alert('请先登录！')
        }
    })




    // addBtn.addEventListener('click', function () {
    //     let id = getProductId()
    //     if (id == data.detail.id) {
    //         let id = data.detail.id
    //         let title = data.detail.title
    //         let price = data.detail.tbOriginPrice
    //         let nickname = data.detail.shop.nickname
    //         let img = data.detail.image
    //         let singlePrice = 0
    //         let obj = {
    //             id,
    //             title,
    //             nickname,
    //             price,
    //             num: 1,
    //             sumPrice: price,
    //             img
    //         }
    //         if (list.length > 0) {
    //             let reaptList = list.some(item => item.id == id)
    //             //！！隐式转换一定为布尔值
    //             if (!!reaptList) {
    //                 list.forEach(item => {
    //                     if (item.id == id) {
    //                         item.num = item.num + 1
    //                     }
    //                 })
    //             } else {
    //                 list.push(obj)
    //             }
    //         } else {
    //             list.push(obj)
    //         }
    //         localStorage.setItem('PANDACART', JSON.stringify(list))
    //         if (confirm('加入购物车成功，是否要调转去购物车？')) {
    //             location.href = 'cart.html'
    //         }
    //     }
    // })


}

/******---------------------**4*放大镜*-----------------------------*****/
function onGlass(data) {
    let mask = document.querySelector('.mask')
    let showBox = document.querySelector('.m-show')
    let showBoxImg = document.querySelector('.m-show>img')
    let glassBox = document.querySelector('.g-right-wrap')
    console.log('glassBox', glassBox);
    let bigImg = document.querySelector('.g-right-wrap>img')
    console.log(bigImg);
    let ulEle = document.querySelectorAll('.m-choose>li')
    // 在显示区获取坐标赋值给遮盖层
    showBox.addEventListener('mousemove', e => {
        e = e || window.event
        let target = e.target || e.srcElement
        mask.style.display = 'block'
        glassBox.style.display = 'block'

        //光标位置
        let x = e.offsetX - mask.offsetWidth / 2
        let y = e.offsetY - mask.offsetHeight / 2

        //边界检查
        if (x < 0) x = 0
        if (y < 0) y = 0
        if (x > showBox.offsetWidth - mask.offsetWidth) x = showBox.offsetWidth - mask.offsetWidth
        if (y > showBox.offsetHeight - mask.offsetHeight) y = showBox.offsetHeight - mask.offsetHeight

        //在显示区获取坐标赋值给遮盖层
        mask.style.left = x + 'px'
        mask.style.top = y + 'px'

        // 计算比例
        let bgw = parseInt(window.getComputedStyle(glassBox).width) * parseInt(window.getComputedStyle(showBox).width) / parseInt(window.getComputedStyle(mask).width)
        let bgh = parseInt(window.getComputedStyle(glassBox).height) * parseInt(window.getComputedStyle(showBox).height) / parseInt(window.getComputedStyle(mask).height)
        bigImg.style.width = bgw + 'px'
        bigImg.style.height = bgh + 'px'


        /*发大图片移动 */
        let glassBoxW = parseInt(window.getComputedStyle(glassBox).width)
        let glassBoxH = parseInt(window.getComputedStyle(glassBox).height)
        let maskW = parseInt(window.getComputedStyle(mask).width)
        let maskH = parseInt(window.getComputedStyle(mask).height)
        let movex = x * glassBoxW / maskW
        let movey = y * glassBoxH / maskH

        //移动位置赋值给背景图片
        bigImg.style.left = `${-movex}px`
        bigImg.style.top = `${-movey}px`

    })

    //鼠标移开，遮盖层隐藏
    showBox.addEventListener('mouseout', e => {
        e = e || window.event
        mask.style.display = 'none'
        glassBox.style.display = 'none'
    })

    /**
     * 选项卡
     *     清除所有样式
     *     给自己添加新的样式
     * */
    //循环绑定事件
    for (let i = 0; i < ulEle.length; i++) {
        /***自定义属性**/
        ulEle[i].setAttribute('data-index', i)
        ulEle[i].addEventListener('click', function () {
            //清除样式
            onClear()
            let index = ulEle[i].getAttribute('data-index')
            showBoxImg.src = `${data.detail.descContentList[index].image.url}`
            bigImg.src = `${data.detail.descContentList[index].image.url}`
        })
    }

    //清除样式
    function onClear() {
        for (let i = 0; i < ulEle.length; i++) {
            ulEle[i].className = ''
        }
    }
}

getProductDetail()
